package com.xc.freeapp.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.xc.freeapp.dao.BookingregDao;
import com.xc.freeapp.dao.DoctorDao;
import com.xc.freeapp.dao.RegpatientDao;
import com.xc.freeapp.dao.SchedulingMapper;
import com.xc.freeapp.dao.dataSource.DBContextHolder;
import com.xc.freeapp.entity.Bookingreg;
import com.xc.freeapp.entity.Bookings;
import com.xc.freeapp.entity.Doctor;
import com.xc.freeapp.entity.Hospital;
import com.xc.freeapp.entity.Regpatient;
import com.xc.freeapp.entity.Scheduling;
import com.xc.freeapp.exception.BaseException;
import com.xc.freeapp.service.BookingregService;
import com.xc.freeapp.service.RegpatientService;
import com.xc.freeapp.util.Constant;
import com.xc.freeapp.util.DateUtils;
import com.xc.freeapp.util.SendSMSUtil;
import com.xc.freeapp.utils.enums.SMSTemplateCode;

@Service
public class BookingregServiceImpl implements BookingregService {
   
	Logger log = Logger.getLogger(this.getClass());
	@Autowired
	private  BookingregDao  bookingregdao;
	@Autowired
	RegpatientService regpatientService;
	@Autowired
	private RegpatientDao regpatientDao;
	@Autowired
	private   DoctorDao  doctordao;
	@Autowired
	SchedulingMapper schedulingMapper;
	
	/**
	 * 我的预约查询
	 */

	public List<Bookings> queryAppointment(int userid,PageBounds pageBounds) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		log.info("预约记录查询");
		//查之前 做一个失效处理 改变状态
		Map<String, Object> maps = gettime(userid);
		bookingregdao.updatebookingreg(maps);
		//返回当前这确的预约情况
		return bookingregdao.queryAppointment(userid, pageBounds);
	}
	
    
     /**
      * 手动取消预约
      */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public int cancelAppointment(int Appointment_id,String delflag) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		log.info("取消预约");
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("id", Appointment_id);
		map.put("delflag", delflag);
		int   a=bookingregdao.cancelAppointment(map);
		Bookingreg bookingreg = bookingregdao.selectByPrimaryKey(Appointment_id);
		Scheduling scheduling=new Scheduling();
		scheduling.setDatetime(bookingreg.getRegdate());
		scheduling.setWorks(bookingreg.getRegtime());
		scheduling.setDoctorid(bookingreg.getDoctorid());
		schedulingMapper.reducebookreg(scheduling);
		return  a;
	}
    /**
     * 删除我的预约
     */
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public int deleteByPrimaryKey(Integer id) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		Bookingreg bookingreg = bookingregdao.selectByPrimaryKey(id);
		Scheduling scheduling=new Scheduling();
		scheduling.setDatetime(bookingreg.getRegdate());
		scheduling.setWorks(bookingreg.getRegtime());
		scheduling.setDoctorid(bookingreg.getDoctorid());
		schedulingMapper.reducebookreg(scheduling);
		return bookingregdao.deleteByPrimaryKey(id);
	}
    
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public int insert(Bookingreg bookingreg) throws Exception{
		DBContextHolder.switchDataSourceRW();//切换数据源
		Scheduling scheduling=new Scheduling();
		scheduling.setDatetime(bookingreg.getRegdate());
		scheduling.setWorks(bookingreg.getRegtime());
		scheduling.setDoctorid(bookingreg.getDoctorid());
		
		int count= schedulingMapper.addbookreg(scheduling);
		if(count!=1){
			throw new BaseException(Constant.ERRORCODE_559);
		}
		return bookingregdao.insert(bookingreg);
	}

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public Bookingreg selectByPrimaryKey(Integer id) {
		DBContextHolder.switchDataSourceRW();//切换数据源
		return bookingregdao.selectByPrimaryKey(id);
	}
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor=Exception.class)
	public Boolean saveBookingReg(Bookingreg bookingreg, Hospital hospital,Regpatient regpatient ) throws Exception {
		DBContextHolder.switchDataSourceRW();//切换数据源
		
		Scheduling scheduling=new Scheduling();
		scheduling.setDatetime(bookingreg.getRegdate());
		scheduling.setWorks(bookingreg.getRegtime());
		scheduling.setDoctorid(bookingreg.getDoctorid());
		int count= schedulingMapper.addbookreg(scheduling);
		if(count!=1){
			throw new BaseException(Constant.ERRORCODE_559);
		}
		
		Random random = new Random();
		String verCode ="REG_";
		for(int i=0;i<8;i++){
			verCode=verCode+random.nextInt(10);
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String regdate = format.format(bookingreg.getRegdate());
		if(bookingreg.getRegtime()==1){
			regdate+=" 上午";
		}else  if(bookingreg.getRegtime()==2){
			regdate+=" 下午";
		}else if(bookingreg.getRegtime()==3){
			regdate+=" 晚上";
		}
		String [] verCodeArray={verCode,hospital.getName(),regdate};
		try{
			SendSMSUtil.sendCode(regpatient.getTelphone(), verCodeArray,SMSTemplateCode.YU_YUE_GUA_HAO);
		}catch(Exception e){
			log.error("发送短信出错");
		}
		bookingreg.setRegcode(verCode);
		bookingregdao.insert(bookingreg);
		return true;
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor=Exception.class)
	public Boolean saveBookingRegV2(Bookingreg bookingreg, Hospital hospital,Regpatient regpatient ) throws Exception {
		DBContextHolder.switchDataSourceRW();//切换数据源
		
		Scheduling scheduling=new Scheduling();
		scheduling.setDatetime(bookingreg.getRegdate());
		scheduling.setWorks(bookingreg.getRegtime());
		scheduling.setDoctorid(bookingreg.getDoctorid());
		int count= schedulingMapper.addbookreg(scheduling);
		if(count!=1){
			throw new BaseException(Constant.ERRORCODE_559);
		}
		
		Random random = new Random();
		String verCode ="REG_";
		for(int i=0;i<8;i++){
			verCode=verCode+random.nextInt(10);
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String regdate = format.format(bookingreg.getRegdate());
		if(bookingreg.getRegtime()==1){
			regdate+=" 9:00-12:00";
		}else  if(bookingreg.getRegtime()==2){
			regdate+=" 14:00-17:00";
		}else if(bookingreg.getRegtime()==3){
			regdate+=" 19:00-22:00";
		}
		String [] verCodeArray={verCode,hospital.getName(),regdate};
		try{
			SendSMSUtil.sendCode(regpatient.getTelphone(), verCodeArray,SMSTemplateCode.YU_YUE_GUA_HAO);
		}catch(Exception e){
			log.error("发送短信出错");
		}
		bookingreg.setRegcode(verCode);
		bookingregdao.insert(bookingreg);
		return true;
	}
	
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor=Exception.class)
	public Map<String,Object> saveBookingRegAndPaitent(Bookingreg bookingreg,Regpatient regpatient, Hospital hospital) throws Exception {
		DBContextHolder.switchDataSourceRW();//切换数据源
		Scheduling scheduling=new Scheduling();
		scheduling.setDatetime(bookingreg.getRegdate());
		scheduling.setWorks(bookingreg.getRegtime());
		scheduling.setDoctorid(bookingreg.getDoctorid());
		int count= schedulingMapper.addbookreg(scheduling);
		if(count!=1){
			throw new BaseException(Constant.ERRORCODE_559);
		}
		
		Map<String,Object> map=new HashMap<String, Object>();
				Integer patinetid = regpatient.getId();
		Integer userid = bookingreg.getUserid();
		bookingreg.setCreateby(userid);
		bookingreg.setUpdateby(userid);
		Random random = new Random();
		String verCode ="REG_";
		for(int i=0;i<8;i++){
			verCode=verCode+random.nextInt(10);
		}
		bookingreg.setRegcode(verCode);
		if(patinetid!=null){//就诊人是选择的
			bookingreg.setPatientid(patinetid);
			bookingregdao.insert(bookingreg);
			regpatientDao.updateByPrimaryKey(regpatient);
		}else{//就诊人是新增的
			regpatient.setCreateby(userid);
			regpatient.setUpdateby(userid);
			PageBounds pageBounds=new PageBounds(1,1000);
			List<Regpatient> regpatients = regpatientService.selectByUserId(userid, pageBounds);
			try{
				regpatientDao.insert(regpatient);
			}catch(Exception e){
				log.info("插入就诊人失败,就诊人已经存在");
				throw new BaseException(Constant.ERRORCODE_557);
			}
			if("t".equals(regpatient.getIsdefault())){
				for (Regpatient regpatient2 : regpatients) {
					regpatient2.setIsdefault("f");
					regpatientService.updateByPrimaryKey(regpatient2);
				}
			}
			int id = regpatient.getId();
			bookingreg.setPatientid(id);
			bookingregdao.insert(bookingreg);
		}
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String regdate = format.format(bookingreg.getRegdate());
		if(bookingreg.getRegtime()==1){
			regdate+="上午";
		}else  if(bookingreg.getRegtime()==2){
			regdate+="下午";
		}else if(bookingreg.getRegtime()==3){
			regdate+="晚上";
		}
		String [] verCodeArray={verCode,hospital.getName(),regdate};
		try{
			SendSMSUtil.sendCode(regpatient.getTelphone(), verCodeArray,SMSTemplateCode.YU_YUE_GUA_HAO);
		}catch(Exception e){
			log.error("发送短信出错");
		}
		Bookingreg bookingregRet = bookingregdao.selectByPrimaryKey(bookingreg.getId());
		Regpatient regpatientRet =regpatientDao.selectByPrimaryKey(regpatient.getId());
		Integer  doctorId = bookingregRet.getDoctorid();
		Doctor doctor =doctordao.getdoctor(String.valueOf(doctorId));
		map.put("bookingreg", bookingregRet);
		map.put("regpatient", regpatientRet);
		map.put("doctor", doctor);
		
		return map;
	}
	/**
	 * 帮助方法,用来给我的预约中状态改变提供必要信息
	 * @param userid
	 * @return 当前时间,及状态
	 */
	public  Map<String,Object>   gettime(int userid)
	{
		DBContextHolder.switchDataSourceRW();//切换数据源
		Map<String, Object>  maps=new  HashMap<String, Object>();
		   //获取当前系统时间
		   String  date=DateUtils.formatDateToString(new Date());
		   //截取当前的日期
		   String  datetime=date.substring(0,10);
		   //截取当前的小时数
		   int  time=Integer.parseInt(date.substring(11, 13));
		   //默认为1,这里与数据库相对应.1:早上2:中午3:晚上
		   int  status=1;
		   if(time>12){
			   status=2;
		   }
			   
		   if(time>17){
			   status=3;
		   }
		
		   if(time>22){
			   status=4;  
		   }
			  
		   maps.put("datetime",datetime);
		   maps.put("status",status);
		   maps.put("userid", userid);
		   return  maps;
	}

}
